<?php


namespace App\Http\Controllers\Admin;


use App\Models\Lottery;
use Illuminate\Http\Request;

class LotteryController extends BaseController
{

    public function __construct(Request $request,Lottery $lottery){
        $this->requset = $request;
        $this->lottery = $lottery;
    }

    /**
     * 抽奖列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        $page = $this->requset->get('page',1);
        $size = $this->requset->get('size',20);

        $count = $this->lottery->count();
        $list = $this->lottery->offset(($page-1)*$size)->limit($size)->get()->toArray();

        return $this->buildSuccess([
            'list' => $list,
            'count' => $count
        ]);
    }

    public function show($id)
    {
        $data = $this->lottery->findOrFail($id);
        return $this->buildSuccess($data);
    }

    public function store()
    {
        $data = $this->requset->all();
        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);
        if(Lottery::create($data))
            return $this->buildSuccess();
        else
            return $this->buildError();
    }

    public function update($id)
    {
        $model = Lottery::findOrFail($id);
        $data = $this->requset->all();
        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);
        if($model->update($data))
            return $this->buildSuccess();
        else
            return $this->buildError();
    }

    public function destroy()
    {
        $id = $this->requset->get('id','');
        if(!$id)
            return $this->buildError(1,'参数错误');
        
        $id = json_decode($id,true);

        if(Lottery::destroy($id))
            return $this->buildSuccess();
        else
            return $this->buildError();
    }

}